<?php

namespace app\admin\model;



use app\admin\model\shop\OrderGoods;
use app\api\model\Order;


use app\admin\data\sdk\yilianyun\Config\YlyConfig;
use app\admin\data\sdk\yilianyun\Api\PrintService;
use think\Exception;
require_once ROOT_PATH.'application/admin/data/sdk/yilianyun/Config/YlyConfig.php';
require_once ROOT_PATH.'application/admin/data/sdk/yilianyun/Api/PrintService.php';

class PrinterOrder
{

    public function printOrder($date,$ids)
    {
        //$date = '2024-11-28';
        $where = ['id'=>['in',$ids]];
        if ($date)$where['date'] = $date;
        $order_list = Order::with(['orderGoods'])
            ->where($where)
            //->where(['date'=>$date])
            //->where('id','in',$ids)
            ->select();

        $printer_info =  Printer::where('status','normal')->find();
        foreach ($order_list as $v) {
            $this->Ylyprint($v, $printer_info);
        }
        return true;
    }

    /**
     * 易联云打印
     * @param $order_info
     * @param $printer
     * @param $shop_info
     */
    public function Ylyprint($order_info, $printer)
    {

        $config = new YlyConfig($printer['open_id'], $printer['apikey']);

        $user = User::get($order_info['user_id']);

        $printer_model = new YlyPrinter();
        $access_token = $printer_model->getYlyToken($config);

        $machine_code = $printer['printer_code'];    //商户授权机器码
        $origin_id = $order_info['order_sn'];        //内部订单号(32位以内)

        /**文本接口开始**/
        $print = new PrintService($access_token, $config);
        $content = "<MN>" . $printer['print_num'] . "</MN>";

        //商城名称
        $name = \app\common\model\Config::get(['name'=>'name'])->value;
        $content .= "<FH2><FS><center>" . $name . "</center></FS></FH2>";
        $content .= str_repeat('.', 32);

        $content .= "配送日期:" . $order_info['date'] . "\n";
        $content .= "配送时间段:" . $order_info['shippingtime'] . "\n";
        $content .= "下单时间:" . date("Y-m-d H:i", $order_info['paytime']) . "\n";
        $content .= "订单编号:" . $order_info['order_sn'] . "\n";

        if ($user['is_incubator']&&$user['can_print']){
            $content .= "保温箱数量:" . $user['incubator_num'] . "\n";
            $user->can_print = 0;
            $user->save();
        }

        $content .= "详细地址:" . $order_info['detail_address'] . "\n";


        $content .= str_repeat('.', 32);
        $content .= "<table>";
        $content .= "<tr><td>商品名称</td><td></td><td>数量</td><td>金额</td></tr>";
        $content .= "</table>";
        $content .= str_repeat('.', 32);
        $content .= "<table>";
        $goods_num = 0;
        foreach ($order_info['order_goods'] as $goods) {

            $goods_num+=$goods['nums'];
            if ($goods['attrdata']){
                $goods_title = $goods['title'].'('.$goods['attrdata'].')';
            } else {
                $goods_title = $goods['title'];
            }

            $sku_name_list = $this->r_str_pad_1($goods_title, 7);
            foreach ($sku_name_list as $index => $value) {
                if ($index == 0) {
                    $content .= "<tr><td>" . $value . "</td><td></td><td>x" . $goods['nums'] . "</td><td>￥" . $goods['realprice'] . "</td></tr>";
                } else {
                    $content .= "<tr><td>" . $value . "</td></tr>";
                }
            }
        }
        $content .= "</table>";
        $content .= str_repeat('.', 32);
        if ($order_info["goodsprice"] > 0) {
            $content .= "商品总额：￥" . $order_info["goodsprice"] . "\n";
        }
        if ($order_info["coupon_money"] > 0) {
            $content .= "店铺优惠券：￥" . $order_info["coupon_money"] . "\n";
        }
        if ($order_info["discount"] > 0) {
            $content .= "折扣：￥" . $order_info["coupon_money"] . "\n";
        }

        //if ($order_info["goods_num"] > 0) {
        $content .= "订单共" . $goods_num . "件商品，总计: ￥" . $order_info['amount'] . "，实付: ￥" . $order_info['payamount'] . " \n";
        //}
        $content .= str_repeat('.', 32);

        /******************** 备注信息 **************************/
        //买家留言

        $content .= "<FH2>买家留言：" . $order_info["memo"] . "</FH2>\n";
        $content .= str_repeat('.', 32);


        /******************** 买家信息 **************************/
        //买家姓名

        $content .= "" . $order_info["receiver"] . "\n";

        //联系方式

        $content .= "" . $order_info["mobile"] . "\n";

        //地址

        $content .= "" . $order_info['address'] . "\n";


        try {
            $print->index($machine_code, $content, $origin_id);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }


    /**
     * 补齐空格
     * 每n个中文字符长度为一个数组元素
     */
    private function r_str_pad_1($input, $n = 7)
    {
        $string = "";
        $count = 0;
        $c_count = 0;
        $arr = array();
        for ($i = 0; $i < mb_strlen($input, 'UTF-8'); $i++) {
            $char = mb_substr($input, $i, 1, 'UTF-8');
            $string .= $char;
            if (strlen($char) == 3) {
                $count += 2;
                $c_count++;
            } else {
                $count += 1;
            }
            if ($count >= $n * 2) {
                $arr[] = $string;
                $string = '';
                $count = 0;
                $c_count = 0;
            }
        }
        if ($count < $n * 2) {
            $string = str_pad($string, $n * 2 + $c_count);
            $arr[] = $string;
        }
        return $arr;
    }

    public function testPrint($printer_id)
    {
        $printer_info =  Printer::get($printer_id);
        $res = $this->testYlyprint($printer_info);

        return $res;
    }

    /**
     * 测试
     * @param $printer
     * @return array
     */
    public function testYlyprint($printer)
    {
        $config = new YlyConfig($printer['open_id'], $printer['apikey']);

        $printer_model = new YlyPrinter();
        $access_token = $printer_model->getYlyToken($config);

        $machine_code = $printer['printer_code'];    //商户授权机器码
        $origin_id = date('YmdHis').rand(1,999);        //内部订单号(32位以内)

        /**文本接口开始**/
        $print = new PrintService($access_token, $config);

        $content = "<MN>" . $printer['print_num'] . "</MN>";

        $content .= "<center>小票名称</center>";
        $content .= str_repeat('.', 32);
        $content .= "<FH2><FS><center>商城名称</center></FS></FH2>";
        $content .= str_repeat('.', 32);

        $content .= "订单时间:" . date("Y-m-d H:i") . "\n";
        $content .= "订单编号:" . $origin_id . "\n";

        $content .= str_repeat('.', 32);
        $content .= "<table>";
        $content .= "<tr><td>商品名称</td><td></td><td>数量</td><td>金额</td></tr>";
        $content .= "</table>";
        $content .= str_repeat('.', 32);

        $content .= "<table>";
        $content .= "<tr><td>烤土豆(超级辣)</td><td></td><td>x3</td><td>5</td></tr>";
        $content .= "<tr><td>烤豆干(超级辣)</td><td></td><td>x2</td><td>10</td></tr>";
        $content .= "<tr><td>烤鸡翅(超级辣)</td><td></td><td>x3</td><td>15</td></tr>";
        $content .= "</table>";
        $content .= str_repeat('.', 32);

        $content .= "商品总额：￥30 \n";
        $content .= "订单共8件商品，总计: ￥30 \n";
        $content .= str_repeat('.', 32);

        /******************** 备注信息 **************************/
        //买家留言

        $content .= "<FH2>买家留言：微辣，多放孜然</FH2>\n";
        $content .= str_repeat('.', 32);

        $content .= "<center>谢谢惠顾，欢迎下次光临</center>";
        //dump($content);die;
        try {

            $res = $print->index($machine_code, $content, $origin_id);

            if($res->error == 0){
                return true;
            }else{
                throw new Exception($res->error_description);
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //打印厨房单
    public function printKitchen($date,$ids)
    {
        //$printer_info =  Printer::get($printer_id);
        //$order_info = Order::with(['orderGoods'])->where('id', $order_id)->find();
        $where = [];
        if ($date) $where['o.date'] = $date;

        $goods_list = collection(OrderGoods::alias('og')
            ->join('fa_shop_order o', 'o.id=og.order_id', 'LEFT')
            ->where($where)
            ->where('og.id','in',$ids)
            ->field('og.title,og.nums as num,og.goods_id,og.attrdata,o.date')
            ->select())->toArray();

        $temp_arr = [];
        //遍历二维数组，将name作为键名
        foreach($goods_list as $value){
            $value['num'] = 0;
            $name = $value['goods_id'].$value['attrdata'];
            $temp_arr[$name] = $value;
        }
        //去重后，将数组重新按照数字索引重新排序
        $temp_arr = array_values($temp_arr);
        foreach($temp_arr as $k=>$v){
            $num = 0;
            foreach($goods_list as $kk=>$vv){
                if ($v['goods_id']==$vv['goods_id']&&$v['attrdata']==$vv['attrdata']){
                    $num+=$vv['num'];
                }

            }
            $temp_arr[$k]['num']=$num;
        }

        $printer_list = Printer::where('status','normal')->select();
        foreach ($printer_list as $v) {
            $this->printYlyKitchen($temp_arr, $v,$date);
        }

        return true;
    }

    public function printYlyKitchen($goods_list, $printer,$date)
    {
        $config = new YlyConfig($printer['open_id'], $printer['apikey']);

        $printer_model = new YlyPrinter();
        $access_token = $printer_model->getYlyToken($config);

        $machine_code = $printer['printer_code'];    //商户授权机器码
        $origin_id = date('YmdHis').rand(1,999);        //内部订单号(32位以内)

        /**文本接口开始**/
        $print = new PrintService($access_token, $config);

        $content = "<MN>" . $printer['print_num'] . "</MN>";

        $content .= "<FH2><FS><center>". "日期:" . $date . "</center></FS></FH2>";
        $content .= str_repeat('.', 32);
        $content .= "<table>";
        $content .= "<tr><td>商品名称</td><td></td><td>数量</td></tr>";
        $content .= "</table>";
        $content .= str_repeat('.', 32);

        if ($goods_list) {
            $content .= "<table>";
            $goods_num = 0;
            foreach ($goods_list as $goods) {
                $goods_num+=$goods['num'];
                if ($goods['attrdata']){
                    $goods_title = $goods['title'].'('.$goods['attrdata'].')';
                } else {
                    $goods_title = $goods['title'];
                }
                $sku_name_list = $this->r_str_pad_1($goods_title, 7);
                foreach ($sku_name_list as $index => $value) {
                    if ($index == 0) {
                        $content .= "<tr><td>" . $value . "</td><td></td><td>x" . $goods['num'] . "</td></tr>";
                    } else {
                        $content .= "<tr><td>" . $value . "</td></tr>";
                    }
                }
            }
            $content .= "</table>";
        }

        try {

            $res = $print->index($machine_code, $content, $origin_id);

            if($res->error == 0){
                return true;
            }else{
                throw new Exception($res->error_description);
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}